<?php
/**
 * 公共函数
 * power by huanran.zhao
 * QQ: 523994553
 * 2012-06-21
 */
class FunctionsApp extends CommonApp{

	/**
	 * 设置分页每页显示数目
	 * @method AJAX->$_GET
	 * @param int pagesize
	 * @return echo string
	 */
	public function setPageSizeAct(){
		$pagesize = My::arr2var($_GET,'pagesize');
		if(!My::is_id($pagesize)) $pagesize = 10;
		$_SESSION['pagesize'] = $pagesize;
		$this->ajaxReturn(200,'操作成功!');
	}

	/**
	 * ajax修改字段值 (结合模板public/share/plug/editable/editable.html)
	 * @method AJAX->$_REQUEST
	 * @param mixed params 加密参数串(table=config&field=ordering&id=1)
	 * @param string value 字段值
	 */
	public function editableSaveAct(){
		//print_r($_REQUEST);exit;
		//分析基本参数(table=xxx&id=xxx&field=xxx&id=1)
		$params = I('request.params');
		if(!$params=My::decode($params)) exit("参数错误(params)");
		$params = str_replace('/','&',$params);//由于smarty模板预先编译的原则导致参数的&被替换为/了
		parse_str($params,$params);
		if(empty($params['table']) or !My::is_table($params['table']))	exit("参数有误(table)");
		if(empty($params['field']))	exit("参数有误(field)");
		if(empty($params['id']) OR !My::is_id($params['id']))	exit("参数有误(id)");
		$value = I('request.value');
		//当前数据库表不是以id为唯一标识时
		if(strpos($params['field'], '.') !== false){
			$field_id = explode('.',$params['field']);
			if(isset($field_id[0])) $params['field']=$field_id[0];
			if(isset($field_id[1])) $params['AID']=$field_id[1];
		}
		if(empty($params['AID'])) $params['AID'] = 'id';
		//准备入库
		$where = "{$params['AID']}={$params['id']}";
		//读取当前要操作的数据
		$result = DB($params['table'])->where($where)->find();
		$result['params'] = My::decodeJson(isset($result['params'])?$result['params']:'');
		//只更改参数
		if(substr($params['field'],0,9)=='[params]['){
			$params['field'] = str_replace(array('[',']'),array("['","']"),$params['field']);
			eval("\$result{$params['field']}='{$value}';");
			//设置params表参数
			My::setParams($params['table'],$result['params'],$params['id']);
			//主表的params字段
			DB($params['table'])->where($where)->clear()->save(array('params'=>$result['params']));
		}
		//正常主表内容更改
		else{
			DB($params['table'])->where($where)->clear()->save(array($params['field']=>$value));
		}
	}
	
	/**
	 * 设置刷新退出时间
	 */
	public function setLoginoutTimeAct(){
		header('Content-type:application/x-javascript');
		$id = My::user('userid');
		if(My::is_id($id)){
			DB('user')->where("id={$id}")->save(array('loginout_time'=>date("Y-m-d H:i:s")));
		}
	}
	
	/**
	 * ajax修改一定字段的值
	 * 复写self::editableSaveAct();函数
	 */
	public function setValueAct(){
		self::editableSaveAct();
		$this->ajaxReturn(200,'修改成功!');
		//header("Location:".URL_);
	}

	/**
	 * 拖动保存排序 (结合模板public/share/plug/drag/drag.html)
	 * @method AJAX->$_POST
	 * @param mixed/string params 加密参数串(table=config&field=ordering)
	 * @param string ids ID串(|号分隔)
	 * @param int page_info 当前分页信息(page=2&pagesize=20&sql=select count(*)...)
	 */
	public function dragSaveOrderAct(){
		//分析基本参数(table=config&field=ordering)
		$params = My::arr2var($_POST,'params');
		if(!$params=My::decode($params)) exit("参数错误(params)");
		$params = str_replace('/','&',$params);//由于smarty模板预先编译的原则导致参数的&被替换为/了
		parse_str($params,$params);
		if(empty($params['table']))	exit("参数有误(table)");
		if(empty($params['field']))	exit("参数有误(field)");
		//分析分页参数(page=2&pagesize=20&sql=select count(*)...)
		$page_info = My::arr2var($_POST,'page_info');
		$page_info = My::decode($page_info);
		parse_str($page_info,$page_info);
		$page_info['page'] = isset($page_info['page'])?(int)$page_info['page']:1;//当前页数
		$page_info['pagesize'] = isset($page_info['pagesize'])?(int)$page_info['pagesize']:10;//每页条数
		//print_r($page_info);exit;
		//分析id参数
		$ids = My::arr2var($_POST,'ids');
		if(empty($ids) or !My::is_string($ids, 'n', '|'))	exit("参数有误(ids)");
		$idArr = explode('|',$ids);
		//保存排序
		if(is_array($idArr)){
			if(!My::is_table($params['table'])) exit("数据表不存在({$params['table']})");//判断表是否存在
			foreach($idArr as $key=>$value){
				$key=$page_info['pagesize']*($page_info['page']-1)+$key;//相对于当前页的排序值
				DB($params['table'])->where("id=".intval($value))->clear()->save(array($params['field']=>$key));//排序值为key
			}
		}
	}
	
	/**
	 * 设置图片的标题
	 * @method AJAX->$_POST
	 * @param int id ID值
	 * @param string title 新标题
	 */
	function ajax_set_image_titleAct(){
		//print_r($_POST);
		$id = My::arr2var($_POST,'id');
		if(My::is_id($id) AND My::arr2var($_POST,'title')!=''){
			DB('photo')->where("id={$id}")->clear()->save(array('title'=>My::arr2var($_POST,'title')));
		}
	}

	/**
	 * ipconfig/ifconfig查看网卡IP信息
	 */
	function ipconfig(){
		echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8">';
		echo "(访问的IP地址为: IPv4地址 或 Ip adress)<br>";
		@exec("ipconfig",$arr);
		if(is_array($arr)){
			foreach($arr as $value){
				echo iconv('','utf-8',$value)."<br>";
			}
		}else{
			@exec("ifconfig",$arr);
			if(is_array($arr)){
				foreach($arr as $value){
					echo iconv('','utf-8',$value)."<br>";
				}
			}
		}
	}
	
	function ajax_cityAct(){//by province id get city list from table:city		params:$_POST['province_id']
		$province_id = My::arr2var($_POST,'province_id');
		if(!My::is_id($province_id))	exit('');//id有误
		$result=$this->DB->row_query("select * from city where province_id={$province_id} AND publish=1");
		$str="<option value=''>选择市...</option>";
		foreach($result as $key=>$value){
			$str.="<option value='{$value['city_id']}'>{$value['city_name']}</option>";
		}
		echo $str;
	}

	function deleteAct(){//删除数据(多个可选)
		//echo "<pre>"; print_r($_POST);exit;
		if(empty($_POST)) { $_POST=$_GET; $_POST['check_id'][]=My::is_id(My::arr2var($_POST,'id'))?$_POST['id']:0; }//get删除单条数据时
		if(!My::is_table(My::arr2var($_POST,'table'))) $this->ajaxReturn(200,"表名有误!");
		
		if(isset($_POST['check_id']) AND is_array($_POST['check_id']) && count($_POST['check_id'])>0){
			$str="";
			foreach($_POST['check_id'] as $key=>$value){
				if(My::is_id($value)){
					$recycleId = M('recycle')->set($_POST['table'],$value);
					$ok = DB(My::arr2var($_POST,'table'))->where("id={$value}")->clear()->delete();
					if($ok){
						$str.="ID:{$value} 删除成功!<br>";
					}else{
						//失败时删除回收站
						if($recycleId>0)
							DB('recycle')->where("id={$recycleId}")->delete();
						//结果文字信息
						$str.="ID:{$value} 删除失败!<br>";
					}
				}
			}
			$this->ajaxReturn(200, $str);
		}else{
			$this->ajaxReturn(300, '删除失败!');
		}
	}
	
	/**
	 * 保存排序
	 */
	function save_orderAct() {
		//echo "<pre>"; print_r($_POST);exit;
		if(!My::is_table(My::arr2var($_POST,'table'))) $this->ajaxReturn(300, '表名有误!');
		
		if( is_array($_POST['ids']) && count($_POST['ids'])>0 && count($_POST['ids'])==count($_POST['order']) ){
			foreach($_POST['ids'] as $key=>$value){
				$id = (int)$value;
				DB($_POST['table'])->where("id={$id}")->clear()->save(array('ordering'=>(int)$_POST['order'][$key]));
			}
		}
		$this->ajaxReturn(200, '排序保存成功!');
	}

	/**
	 * 采集单个网页内容
	 * @param string $url
	 */
	public function pickAct(){
		$url = My::arr2var($_POST,'url');
		if(empty($url)) $this->ajaxReturn(300,'URL不能为空!');
		$url_info = parse_url($url);
		$host = isset($url_info['host']) ? $url_info['host'] : '';
		if(empty($host)) $this->ajaxReturn(300,"URL格式错误!");
		$content = Http::curlRequest($url);
		if($content === false) $this->ajaxReturn(300, '无法打开采集的网页！');
		$sw = $ew = '';
		//提取采集规则
		$pickList = DB('datas')->where("`item`='pick' AND publish=1")->cache()->select();
		if(is_array($pickList))
		foreach($pickList as &$value){
			$value['params'] = My::decodeJson($value['params']);
			if(isset($value['params']['url']) AND 'http://'.$host==$value['params']['url']){
				$pick_info = $value;
				break;
			}
		}
		//进行内容匹配
		if(isset($pick_info)){
			//exit($pick_info['params']['rule']);
			$rule_arr = explode('{@body}', $pick_info['params']['rule']);
			$sw = $rule_arr[0];
			$ew = $rule_arr[1];
			if(($lang = $pick_info['params']['charset']) == 'gb2312'){
				 $content = iconv('GBK//IGNORE', 'utf-8', $content);
			}
		}
		// 标题
		$matches = array();
		preg_match_all('/<title>(.*)<\/title>/isU', $content, $matches);
		$data['title'] = isset($matches[1][0]) ? trim($matches[1][0]) : '';
		// 关键字
		preg_match_all('/<meta[\s]+name=[\'"]keywords[\'"] content=[\'"](.*)[\'"]/isU', $content, $matches);
		$data['keywords'] = isset($matches[1][0]) ? trim($matches[1][0]) : '';
		// 描述
		preg_match_all('/<meta[\s]+name=[\'"]description[\'"] content=[\'"](.*)[\'"]/isU', $content, $matches);
		$data['description'] = isset($matches[1][0]) ? trim($matches[1][0]) : '';
		
		if($sw != '' && $ew!=''){
			$start = strpos($content, $sw);
			if($start !== false){
				$end = strpos($content, $ew, $start);
				if($end !== false && $end > $start){
					$content = substr($content, $start+strlen($sw), $end-$start-strlen($sw));
				}
			}
		}
		$data['content'] = $content;
		//dump($data);exit;
		echo json_encode($data);
	}

}